package com.lzx.schedule;

import com.lzx.entity.Ip;
import com.lzx.service.IpService;
import com.lzx.util.CrawlerUtil;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.Random;

public class AutoClickJob extends QuartzJobBean {
    @Autowired
    IpService ipService;

    @Override
    protected void executeInternal (JobExecutionContext jobExecutionContext) throws JobExecutionException {

//        //获取JobDetail中传递的参数
//        String userName = (String) jobExecutionContext.getJobDetail().getJobDataMap().get("userName");
//        String blogUrl = (String) jobExecutionContext.getJobDetail().getJobDataMap().get("blogUrl");

        System.out.println("定时任务执行中");
        String url = "http://www.baidu.com/link?url=GYDo920GT654uMxzrukwLtBQR7QqqNRJo7rObbSXxry8EjKLwbtQ8eC96QO8DMgsYk4gKBYV0kKFbieYY3Gz4MacYhg6Fhs-qJ8cjUj-zdS";
        String html = getHtmlByHttpClient(url);
        System.out.println(html);
    }

    public String getHtmlByHttpClient(String url){
        String html = "";
        BufferedReader bufferedReader = null;
        InputStream in = null;
        try{

            HttpGet get = new HttpGet(url);
            get.setHeader("user-agent"," Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36");

            int  count = ipService.count();
            String flag = "";

            if(count != 0){
                Ip ip = (ipService.getOneByRand()).get(0);
                System.out.println("代理IP" + ip);
                if(CrawlerUtil.runTest(ip)){
                    System.out.println("代理IP有效");
                    flag = "使用代理IP ";
                    HttpHost proxy = new HttpHost(ip.getUrl(),ip.getPort());
                    RequestConfig config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(500).build();
                    get.setConfig(config);
                }else{
                    System.out.println("代理IP无效，已删除,使用本地IP");
                    ipService.removeById(ip.getId());
                }
            }


//            String ip_url = "221.5.80.66";
//            int ip_port = 3128;
//            Ip ip1 = new Ip();
//            ip1.setUrl(ip_url);
//            ip1.setPort(ip_port);
//            if(CrawlerUtil.runTest(ip1)){
//                System.out.println("代理ip测试成功");
//
//                HttpHost proxy = new HttpHost(ip_url,ip_port);
//                RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
//                get.setConfig(config);
//
//            }else{
//                System.out.println("代理ip测试失败");
//            }






            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpResponse response = httpClient.execute(get);

            if(response.getStatusLine().getStatusCode() == 200) {
                html = flag +"执行任务成功";
//                HttpEntity entity = response.getEntity();
//
//                in = entity.getContent();
//
//                bufferedReader = new BufferedReader(new InputStreamReader(in));
//                StringBuffer result = new StringBuffer();
//                String line = null;
//                while((line = bufferedReader.readLine()) != null){
//                    result.append(line);
//                    result.append("\n");
//                }
//                html = result.toString();
            }else{
                System.out.println("任务执行失败");
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(bufferedReader != null){
                    bufferedReader.close();
                }
                if(in != null){
                    in.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return html;
    }
    public String getHtmlByHttpURLConnection(String urlString) {
        StringBuffer stringBuffer = new StringBuffer();
        if (!urlString.startsWith("http")) {
            urlString = "https://" + urlString;
        }
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(urlString);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestProperty("User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
            httpURLConnection.setReadTimeout(2000);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(2000);
            if (httpURLConnection.getResponseCode() == 200) {
                inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream(), "utf-8");

                bufferedReader = new BufferedReader(inputStreamReader);

                String line = "";

                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                    stringBuffer.append("\n");
                }
            } else {
                System.out.println(httpURLConnection.getResponseCode());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {

                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
            } catch (IOException ee) {
                ee.printStackTrace();
            }
        }
        return stringBuffer.toString();
    }
}
